package user_v1

import (
	"context"
	"errors"
	"gf-xb-api/internal/consts"
	"gf-xb-api/internal/dao"
	"gf-xb-api/internal/model/dto"
	"gf-xb-api/internal/model/entity"
	"gf-xb-api/utility/xpermission"
	"gf-xb-api/utility/xstr"

	"github.com/gogf/gf/v2/util/gconv"
	"golang.org/x/crypto/bcrypt"
)

func (s *sUser) Create(ctx context.Context, in dto.UserCreateInput) (output bool, err error) {

	// 密码检查
	if !xstr.IsValidPassword(in.Password) {
		return false, errors.New(consts.INVALID_PASSWORD)
	}

	m := dao.SysUser.Ctx(ctx).Where(dao.SysUser.Columns().Username, in.Username).WhereOr(dao.SysUser.Columns().Mobile, in.Mobile)
	if in.Email != nil && xstr.IsNotBlank(*in.Email) {
		m = m.WhereOr(dao.SysUser.Columns().Email, *in.Email)
	}

	if in.Nickname != nil && xstr.IsNotBlank(*in.Nickname) {
		m = m.WhereOr(dao.SysUser.Columns().Nickname, *in.Nickname)
	}

	count, err := m.Count()
	if err != nil {
		return false, err
	}

	if count > 0 {
		return false, errors.New("新建用户失败：账号/手机号/邮箱/昵称已被使用")
	}

	var data *entity.SysUser
	if err = gconv.Struct(in, &data); err != nil {
		return false, err
	}

	// 密码加密
	passwordHash, err := bcrypt.GenerateFromPassword([]byte(in.Password), bcrypt.DefaultCost)
	if err != nil {
		return false, nil
	}
	data.PasswordHash = string(passwordHash)

	userUUID := xpermission.GetLoginUserUUID(ctx)
	data.CreatedBy = &userUUID
	data.UpdatedBy = &userUUID

	data.Uuid = xstr.GetUUID()
	data.Status = uint(consts.USER_STATUS_ACTIVE) // 这里直接生效

	_, err = dao.SysUser.Ctx(ctx).Data(data).Insert()
	if err != nil {
		return false, err
	}

	return true, nil
}
